package com.sgb.kjwl.view.ui.activity.manage

import android.content.Context
import android.content.Intent
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.contract.model.ContractListSearchBean
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityWebsiteContractListBinding
import com.sgb.kjwl.databinding.ItemWebsiteContractBinding
import com.sgb.kjwl.model.entity.manage.WebsiteContractEntity
import com.sgb.kjwl.viewmodel.manage.WebsiteContractListViewModel
import com.swgk.core.BaseAppHelper
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration

/**
 * 合约列表
 */
class WebsiteContractListActivity : AppActivity() {

    private lateinit var mViewModel : WebsiteContractListViewModel
    private lateinit var mBinding : ActivityWebsiteContractListBinding

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private lateinit var mAdapter : WebsiteContractAdapter
    private var mCompanyNo = ""

    companion object{
        const val KEY_NO = "key_no"
        fun launch(context: Context, companyNo : String){
            val intent = Intent()
            intent.setClass(context, WebsiteContractListActivity::class.java)
            intent.putExtra(KEY_NO, companyNo)
            context.startActivity(intent)
        }
    }

    override fun initView() {
        super.initView()
        if (intent != null){
            mCompanyNo = intent.getStringExtra(KEY_NO)
        }
        if (TextUtils.isEmpty(mCompanyNo)){
            finish()
            return
        }
        mViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(BaseAppHelper.get().instance).create(WebsiteContractListViewModel::class.java)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_website_contract_list)
        mBinding.include.titleView.text = "合约列表"
        mBinding.include.ivBack.setOnClickListener { finish() }
        initRecyclerView()
        mViewModel.mWebsiteContractList.observe(this, {
            if (it != null){
                mAdapter.setNewData(it)
            }
        })
    }

    override fun init() {
        super.init()
        mViewModel.getContractList(mCompanyNo)
    }


    private fun initRecyclerView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mViewModel.getContractList(mCompanyNo)
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = WebsiteContractAdapter(this, R.layout.item_website_contract)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_line)
            )
        )
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val info = ContractListSearchBean.ContractListInfo()
            info.localUrl = mAdapter.getItem(position)!!.localUrl
            info.isTaker = mAdapter.getItem(position)!!.isPostFirstParty() != null
            info.status = mAdapter.getItem(position)!!.status
            info.deadline = mAdapter.getItem(position)!!.deadline
            info.id = mAdapter.getItem(position)!!.id
            info.signTag = mAdapter.getItem(position)!!.signCase
            mViewModel.jumpToSignContractActivity(this, info)
        }
    }




    class WebsiteContractAdapter(mContext : Context, layoutResId : Int) : BaseQuickAdapter<WebsiteContractEntity, BaseViewHolder>(layoutResId){
        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_title_medium))

        private var ssb : SpannableStringBuilder ?= null
        private var mItemBinding : ItemWebsiteContractBinding ?= null
        override fun convert(helper: BaseViewHolder?, item: WebsiteContractEntity?) {
            mItemBinding = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinding != null){
                mItemBinding!!.entity = item
                //setColorSpan(mContext.resources.getString(R.string.website_first_party, item!!.firstPartyName), mItemBinding!!.tvFirstParty)
                if (item!!.isPostFirstParty() != null && item.isPostFirstParty()!!){
                    mItemBinding!!.ivPostFirstParty.visibility = View.VISIBLE
                } else {
                    mItemBinding!!.ivPostFirstParty.visibility = View.GONE
                }
                if (item.isPostFirstParty() != null && !item.isPostFirstParty()!!){
                    mItemBinding!!.ivPostSecondParty.visibility = View.VISIBLE
                } else {
                    mItemBinding!!.ivPostSecondParty.visibility = View.GONE
                }

                if (item.auditStatus == 2){
                    mItemBinding!!.tvApproveStatus.text = "已通过"
                    mItemBinding!!.tvApproveStatus.setTextColor(mContext.resources.getColor(R.color.color_secondary_green))
                } else if (item.auditStatus == 3){
                    mItemBinding!!.tvApproveStatus.text = "已拒绝"
                    mItemBinding!!.tvApproveStatus.setTextColor(mContext.resources.getColor(R.color.color_main))
                } else if (item.auditStatus == 1){
                    mItemBinding!!.tvApproveStatus.text = "审核中"
                    mItemBinding!!.tvApproveStatus.setTextColor(mContext.resources.getColor(R.color.color_secondary_blue))
                } else {
                    mItemBinding!!.tvApproveStatus.text = "/"
                    mItemBinding!!.tvApproveStatus.setTextColor(mContext.resources.getColor(R.color.color_title_small))
                }
                if (item.status == 2){
                    mItemBinding!!.tvStatus.setBgColor(R.color.color_secondary_yellow)
                    if (item.signCase == 7){
                        mItemBinding!!.tvStatus.text = "待我方\n签署"
                    } else if (item.signCase == 6){
                        mItemBinding!!.tvStatus.text = "待对方\n签署"
                    }
                } else if (item.status == 1){
                    mItemBinding!!.tvStatus.setBgColor(R.color.color_secondary_blue)
                    mItemBinding!!.tvStatus.text = "拟定中"
                } else if (item.status == 3){
                    mItemBinding!!.tvStatus.setBgColor(R.color.color_secondary_green)
                    mItemBinding!!.tvStatus.text = "已完成"
                } else if (item.status == 4){
                    mItemBinding!!.tvStatus.setBgColor(R.color.color_tab_two)
                    mItemBinding!!.tvStatus.text = "已过期"
                } else if (item.status == 5){
                    mItemBinding!!.tvStatus.setBgColor(R.color.color_tab_three)
                    mItemBinding!!.tvStatus.text = "已作废"
                }
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

    }

}